package br.com.sbc.filter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.sbc.util.SBCconstantes;

@WebServlet("/fotoPerfil/*")
public class ImagemServlet extends HttpServlet {

	private static final long serialVersionUID = -8786859519538577288L;

	private static final int DEFAULT_BUFFER_SIZE = 10240;

	private String caminhoImagem;

	public void init() throws ServletException {

		this.caminhoImagem = getServletContext().getRealPath("/static/images/usuario/");

	}

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String requestedImage = request.getPathInfo();

		if (requestedImage == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		File foto = new File(caminhoImagem, URLDecoder.decode(requestedImage,"UTF-8"));

		if (!foto.exists()) {
			foto = new File(caminhoImagem, URLDecoder.decode(SBCconstantes.FOTO_PADRAO,"UTF-8"));
			if (!foto.exists()) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
				return;
			}
		}

		String contentType = getServletContext().getMimeType(foto.getName());

		if (contentType == null || !contentType.startsWith("image")) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		response.reset();
		response.setBufferSize(DEFAULT_BUFFER_SIZE);
		response.setContentType(contentType);
		response.setHeader("Content-Length", String.valueOf(foto.length()));
		response.setHeader("Content-Disposition","inline; filename=\"" + foto.getName() + "\"");

		BufferedInputStream input = null;
		BufferedOutputStream output = null;

		try {
			input = new BufferedInputStream(new FileInputStream(foto),DEFAULT_BUFFER_SIZE);
			output = new BufferedOutputStream(response.getOutputStream(),DEFAULT_BUFFER_SIZE);

			byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int length;
			while ((length = input.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
		} finally {
			close(output);
			close(input);
		}
	}

	private static void close(Closeable resource) {
		if (resource != null) {
			try {
				resource.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
